package com.fizz.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
public class DatasourceConfig {

    private static Logger logger = LoggerFactory.getLogger(DatasourceContextHolder.class);

    @Primary
    @Bean(name = "writeDataSource",destroyMethod = "close")
    @ConfigurationProperties(prefix = "write")
    public DataSource writeSource(){

        return new DruidDataSource();
    }

    @Bean(name = "readDataSource",destroyMethod = "close")
    @ConfigurationProperties(prefix = "read")
    public DataSource readSource(){
        return new DruidDataSource();
    }


    @Bean(name = "writeOrReadsqlSessionFactory")
    public SqlSessionFactory sqlSessionFactorys( RoutingDataSourceImpl roundRobinDataSouceProxy)
            throws Exception {
        try {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(roundRobinDataSouceProxy);
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            // 实体类对应的位置
            bean.setTypeAliasesPackage("com.fizz.model.entity");
            // mybatis的XML的配置
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
            return bean.getObject();
        } catch (IOException e) {
            logger.error("" + e);
            return null;
        } catch (Exception e) {
            logger.error("" + e);
            return null;
        }
    }

    @Bean(name = "writeOrReadTransactionManager")
    public DataSourceTransactionManager transactionManager(RoutingDataSourceImpl
                                                                   roundRobinDataSouceProxy) {
        //Spring 的jdbc事务管理器
        DataSourceTransactionManager transactionManager = new
                DataSourceTransactionManager(roundRobinDataSouceProxy);
        return transactionManager;
    }
}
